package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.support.collections.DefaultRedisList;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{

    private String name;
    private StringRedisTemplate stringRedisTemplate;

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true)+"-";
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    //加载脚本
    static {
         UNLOCK_SCRIPT = new DefaultRedisScript<>();
         UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
         UNLOCK_SCRIPT.setResultType(Long.class);
    }

    //set lock thread1 nx ex 10
    @Override
    public boolean tryLock(long timeoutSec) {

        //获取线程标识，表示是哪个线程获取锁，线程标识id是由jvm递增的，集群下不同的jvm可能由相同的线程id
        //可以用uuid区分不同的服务，再用线程id区分线程
        String threadId = ID_PREFIX + Thread.currentThread().getId();

        //获取分布式锁
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        //return success;//这样返回存在空指针
        return Boolean.TRUE.equals(success);//BooleanUtil.isTrue(success);

    }

    @Override
    public void unlock() {
        //调用lua脚本,判断＋删除在脚本中执行，满足原子性
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId()
        );
    }
//    @Override
//    public void unlock() {
//        //先获取线程标识
//        String threadId = ID_PREFIX + Thread.currentThread().getId();
//        //跟redis里的锁比较
//        //获取锁中的标识
//        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
//        //判断标识是否一致,注意这里判断+释放不是原子性的，释放锁时如果被阻塞导致锁超时释放，这时候删除会删除别人的锁。
//        if(threadId.equals(id)){
//            //释放锁
//            stringRedisTemplate.delete(KEY_PREFIX  +name);
//        }
//    }
}
